/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.db.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edi.db.SessionFactory;
import com.edi.db.cfg.Configuration;
import com.edi.db.cfg.Environment;

/**
 * 用来构造和产生不同应用的sessionUtil。
 * 
 * 
 */
public class EdiSessionFactory {
	private static final Log log = LogFactory.getLog(EdiSessionFactory.class);

	private static Map<String, SessionFactory> sessionFactoryMap;

	private static EdiSessionFactory sf;

	private EdiSessionFactory() {
		sessionFactoryMap = new HashMap<String, SessionFactory>();
	}

	public static EdiSessionFactory getInstance() {
		if (sf == null) {
			sf = new EdiSessionFactory();
		}
		return sf;
	}

	public void addSessionFactory(String appName, Configuration configuration) {
		for (SessionFactory sessionFactory : sessionFactoryMap.values()) {
			if (configuration.equals(sessionFactory.getCfg())) {
				log.debug("获取相同session："
						+ configuration.getProperty(Environment.SERVER) + "---"
						+ configuration.getProperty(Environment.DBNAME)
						+ "---appName : " + appName);
				addSessionFactory(appName, sessionFactory);
				return;
			}
		}
		SessionFactory sessionFactory = new SessionFactory(configuration);
		log.debug("新建一个dbsession："
				+ configuration.getProperty(Environment.SERVER) + "---"
				+ configuration.getProperty(Environment.DBNAME)
				+ "---appName : " + appName);
		addSessionFactory(appName, sessionFactory);
	}

	public void addSessionFactory(String appName, SessionFactory sessionFactory) {
		sessionFactoryMap.put(appName, sessionFactory);
	}

	public SessionUtil getSessionUtil(String appName) {
		//		 log.debug(" sessionFactoryMap ="+sessionFactoryMap.keySet().size());
		//		 Iterator<String> it=sessionFactoryMap.keySet().iterator();
		//		 while(it.hasNext()){
		//		 String app=it.next();
		//		 log.debug("sessionFactoryMap it = "+app );
		//		 log.debug(" factory ="+sessionFactoryMap.get(app));
		//		 }

		SessionFactory sessionFacotry = sessionFactoryMap.get(appName);
		//		 log.debug("sessionFacotry ==null"+appName+" // "+(sessionFacotry==null));
		return sessionFacotry == null ? null : new SessionUtil(sessionFacotry);
	}

}
